import React, {useEffect, useState} from "react";
import type {LendLogItem} from "@/pages/m/LendLogs/data";
import {Avatar, message} from "antd";
import {deleteLendLog, queryLendLog, addLendPaybackLog, updateLendLog} from "@/pages/m/LendLogs/service";
import dayjs from "dayjs";
import PaybackForm from "@/pages/m/LendLogs/components/PaybackForm";
import PaybackLogForm from "@/pages/m/LendLogs/components/PaybackLogForm";
import UpdateForm from "@/pages/m/LendLogs/components/UpdateForm";
import Style from "./style.less"
import {Dialog, DotLoading, InfiniteScroll, List, SwipeAction, Toast} from "antd-mobile";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: any) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteLendLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        Toast.show({
          content: res.message,
          icon: "success"
        })
        return true;
      } else {
        Toast.show({
          content: res.message,
          icon: "fail"
        })
        return false;
      }
    } else {
      Toast.show({
        content: '请求超时，请稍后重试',
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '请求超时，请稍后重试',
      icon: "fail"
    })
    return false;
  }
};

/**
 * 还钱记录更新节点
 *
 * @param fields
 * @param currentRow
 */

const handlePaybackLogUpdate = async (fields: any, currentRow?: LendLogItem) => {
  const hide = message.loading('正在记录。。。。。。');

  try {
    const res = await addLendPaybackLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '请求超时，请稍后重试',
      icon: "fail"
    })
    return false;
  }
};
/**
 * 流水更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleLogUpdate = async (fields: any, currentRow?: LendLogItem) => {
  const hide = message.loading('正在修改');

  try {
    const res = await updateLendLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '请求超时，请稍后重试',
      icon: "fail"
    })
    return false;
  }
};
export type Props = {
  update: boolean;
};

const LendLogs: React.FC<Props> = (props: {update: boolean}) => {

  // 还钱窗口
  const [currentRow, setCurrentRow] = useState<LendLogItem>();
  const [paybackModalVisable, handlePaybackModalVisable] = useState<boolean>(false)
  const [paybackLogModalVisable, handlePaybackLogModalVisable] = useState<boolean>(false)

  /** 更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  // 获取流水数据
  const [page, setPage] = useState(1)
  const [data, setData] = useState<LendLogItem[]>(new Array())
  const [hasMore, setHasMore] = useState(true)

  async function loadMore(firstPage = false) {

    let currentPage = page
    if (firstPage){
      currentPage = 1
    }

    // 从后台获取流水
    const res = await queryLendLog({
      current: currentPage, pageSize: 10
    });
    if (res.status === "done"){
      if (currentPage === 1){

        // 重载数据
        const emptyList = [...data]
        emptyList.splice(0, emptyList.length)
        res.data?.map((item)=>{
          emptyList.push(item)
        })
        setData(emptyList)
      }else {

        // 插入数据
        const newData = [...data];
        res.data?.map((item)=>{
          newData.push(item)
        })
        setData(newData)
      }

      // 计算是否有下一页
      setHasMore(res.total > 10 * currentPage)

      // 下一页
      setPage(currentPage + 1)
    }
  }

  // 更新数据
  const [needUpdate, setNeedUpdate] = useState(false)
  useEffect(()=>{
    loadMore(true)
  }, [props, needUpdate])

  // 自定义下拉获取
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const InfiniteScrollContent = ({ hasMore }: { hasMore?: boolean }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 我是有底线的 ---</span>
        )}
      </>
    )
  }

  // 滑动操作
  const rightActions: any[] = [
    {
      key: 'payback',
      text: '还钱',
      color: '#1890ff',
      onClick: ()=>{
        handlePaybackModalVisable(true)
      }
    },
    {
      key: 'paybackLog',
      text: '记录',
      color: 'green',
      onClick: ()=>{
        handlePaybackLogModalVisable(true)
      }
    },
    {
      key: 'edit',
      text: '修改',
      color: '#8c8c8c',
      onClick: ()=>{
        handleUpdateModalVisible(true)
      }
    },
    {
      key: 'delete',
      text: '删除',
      color: 'danger',
      onClick: ()=>{
        Dialog.show({
          content: "真的要删除？",
          closeOnAction: true,
          actions: [
            [
              {
                key: 'cancel',
                text: '取消',
              },
              {
                key: 'delete',
                text: '删除',
                bold: true,
                danger: true,
                onClick: async ()=>{
                  // 执行删除操作
                  const success = await handleSingleRemove(currentRow);
                  if (success) {
                    // 删除成功，从data中删除此行数据
                    const newData = [...data]
                    newData.map((item)=>{
                      if (item.id == currentRow?.id){
                        // 删除
                        newData.splice(newData.indexOf(item), 1)
                        setData(newData)
                      }
                    })
                  }
                }
              },
            ],
          ]
        })

      }
    },
  ]
  return (
    <>
      <List
        style={{
          position: "relative",
          width: `100%`,
          "--font-size": "15px"
        }}
      >
        {data.map((item) => {
          if (item.date) {
            // 有日期的，插入一个日期列
            return (
              <>
                <List.Item key={"item_" + item.id} className={Style.itemBackground}>
                  <div className={Style.inlineBlock}>
                    <b className={Style.days}>{dayjs(item.date).format("DD ")}</b>
                  </div>
                  <div className={Style.monthAndYear}>
                    {dayjs(item.date).format("/ MM / YYYY")}
                  </div>
                </List.Item>
                <SwipeAction
                  key={item.id}
                  rightActions={rightActions}
                  onActionsReveal={() => {
                    setCurrentRow(item)
                  }}
                >
                  <List.Item
                    key={"item" + item.id}
                    prefix={<Avatar src={"/static/icons/maifangshoufang.png"}/>}
                    description={<span>{dayjs(item.oweTime).format("HH:mm")} - <span style={{color: "#8c8c8c", fontSize: 8}}>{item.remark}</span></span>}
                    extra={
                      <>
                        <a
                          onClick={()=>{Toast.show({content: "这是借出金额。"})}}
                          className={Style.outMoney}
                        >
                          ¥ {item.oweMoney}
                        </a>

                        <a
                          onClick={()=>{Toast.show({content: "这是收回金额。"})}}
                          className={Style.inMoney}
                        >
                          ¥ {item.paybackMoney}
                        </a>
                      </>
                    }
                  >
                    {item.toWho}
                  </List.Item>
                </SwipeAction>
              </>
            )
          }else{

            // 同一天的不同时间的，只返回时间的
            return (
              <SwipeAction
                key={item.id}
                rightActions={rightActions}
                onActionsReveal={() => {
                  setCurrentRow(item)
                }}
              >
                <List.Item
                  key={item.id}
                  prefix={<Avatar src={"/static/icons/maifangshoufang.png"}/>}
                  description={<span>{dayjs(item.oweTime).format("HH:mm")} - <span style={{color: "#8c8c8c", fontSize: 8}}>{item.remark}</span></span>}
                  extra={
                    <>
                      <a
                        onClick={()=>{Toast.show({content: "这是借出金额。"})}}
                        className={Style.outMoney}
                      >
                        ¥ {item.oweMoney}
                      </a>

                      <a
                        onClick={()=>{Toast.show({content: "这是收回金额。"})}}
                        className={Style.inMoney}
                      >
                        ¥ {item.paybackMoney}
                      </a>
                    </>
                  }
                >
                  {item.toWho}
                </List.Item>
              </SwipeAction>
            )
          }
        })}
      </List>
      <InfiniteScroll
        loadMore={loadMore}
        hasMore={hasMore}
        threshold={0}
      >
        <InfiniteScrollContent hasMore={hasMore} />
      </InfiniteScroll>
      <div style={{height: 100, width: `100%`, position: "relative"}}/>

      <PaybackForm
        onCancel={()=>{
          handlePaybackModalVisable(false)
          setCurrentRow(undefined)
        }}
        onSubmit={async (value)=>{
          const success = await handlePaybackLogUpdate(value, currentRow);
          if (success){
            handlePaybackModalVisable(false)
            setCurrentRow(undefined)

            // 更新数据
            setNeedUpdate(!needUpdate)
          }
        }}
        modalVisible={paybackModalVisable}
        values={currentRow || {}}
      />
      <PaybackLogForm
        onCancel={()=>{
          handlePaybackLogModalVisable(false)
          setCurrentRow(undefined)

          // 更新数据
          setNeedUpdate(!needUpdate)
        }}
        onSubmit={async () =>{
          handlePaybackLogModalVisable(false)
          setCurrentRow(undefined)

          // 更新数据
          setNeedUpdate(!needUpdate)
        }}
        modalVisible={paybackLogModalVisable}
        values={currentRow || {}}
      />
      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
        }}
        onSubmit={async (value)=>{
          const success = await handleLogUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)

            // 更新数据
            setNeedUpdate(!needUpdate)
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
    </>

  )
}
export default LendLogs;
